var util = require('../../utils/util.js');
var api = require('../../config/api.js');


var app = getApp();

Page({
  data: {
    id: 0,
    brand: {},
    goodsList: [],
    page: 1,
    size: 10
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    var that = this;
    that.setData({
      id: parseInt(options.id)
    });
    this.getBrand();
  },
  getBrand: function () {
    let that = this;
    util.request(api.BrandDetail, { id: that.data.id }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          brand: res.data.brand
        });

        that.getGoodsList();
      }
    });
  },
  getGoodsList() {
    var that = this;

    util.request(api.GoodsList, { brandId: that.data.id, page: that.data.page, size: that.data.size})
      .then(function (res) {
        if (res.errno === 0) {
          let goodsList = that.data.goodsList;
          if (that.data.page != 1) {
            //上拉翻页
            goodsList.push.apply(goodsList, res.data.goodsList);
          } else {
            //下拉刷新
            goodsList = res.data.goodsList;
          }
          that.setData({
            goodsList: goodsList
          });
        }
      });
  },
  onReady: function () {
    // 页面渲染完成

  },
  onShow: function () {
    // 页面显示

  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  /**
  * 下拉刷新
  */
  onPullDownRefresh: function () {
    let that = this;
    that.setData({
      page: 1
    })
    that.getGoodsList();
    wx.stopPullDownRefresh();
  },
  /**
   * 上拉触底
   */
  onReachBottom: function () {
    let that = this;
    if (that.data.goodsList.length % that.data.size === 0) {
      let goodsList = that.data.goodsList;
      new Promise(function (resolve, reject) {
        that.setData({
          page: that.data.page + 1
        })
        resolve();
      }).then(() => {
        that.getGoodsList();
      })
    }
  }
})